<template>
  <div class="nutrition-page">
    <div class="header">
      <h1>营养成分分析</h1>
      <div class="search-bar">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索食物..."
          @keyup.enter="filterFoods" 
          class="search-input"
        >
        <button @click="filterFoods" class="search-btn">
          搜索
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在加载数据...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-else-if="error" class="error-message">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ error }}</p>
    </div>
    
    <!-- 卡片列表 -->
    <div v-else class="food-cards">
      <div 
        v-for="(item, index) in filteredFoods" 
        :key="item.food_id" 
        class="food-card"
      >
        <div class="card-header">
          <h3>{{ item.name }}</h3>
          <span class="calories">{{ item.calories || 'N/A' }} kcal</span>
        </div>
        <div class="nutrition-facts">
          <div class="fact-item">
            <span class="fact-label">蛋白质</span>
            <span class="fact-value">{{ item.protein || 'N/A' }}g</span>
          </div>
          <div class="fact-item">
            <span class="fact-label">脂肪</span>
            <span class="fact-value">{{ item.fat || 'N/A' }}g</span>
          </div>
          <div class="fact-item">
            <span class="fact-label">碳水</span>
            <span class="fact-value">{{ item.carbohydrate || 'N/A' }}g</span>
          </div>
        </div>
        <div class="card-content-description">
          <p>{{ item.description || '暂无描述' }}</p>
        </div>
        <!-- 图表容器 -->
        <div class="nutrition-chart" :ref="el => chartRefs[index] = el"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch, onUnmounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  DatasetComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册ECharts组件
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  DatasetComponent,
  CanvasRenderer
]);

// 营养成分颜色配置
const NUTRITION_COLORS = {
  protein: '#5470C6',   // 蓝色 - 蛋白质
  fat: '#FAC858',      // 橙色 - 脂肪
  carbohydrate: '#91CC75', // 绿色 - 碳水化合物
};

const foodList = ref([]);
const searchQuery = ref('');
const loading = ref(true);
const error = ref(null);
const chartRefs = ref([]); // 存储图表DOM引用
const charts = ref({}); // 存储ECharts实例

// 计算属性实现搜索过滤
const filteredFoods = computed(() => {
  if (!searchQuery.value.trim()) {
    return foodList.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return foodList.value.filter(item => 
    item.name.toLowerCase().includes(query)
  );
});

// 获取食物列表数据
onMounted(async () => {
  try {
    // 模拟数据（用于测试，实际使用时请注释掉）
    // foodList.value = [
    //   { food_id: 1, name: '苹果', calories: 52, protein: 0.3, fat: 0.2, carbohydrate: 13.8 },
    //   { food_id: 2, name: '牛肉', calories: 250, protein: 26.1, fat: 15.5, carbohydrate: 0 },
    // ];
    
    const response = await axios.get('http://localhost:8080/MDMS0214_war/food/all');
    foodList.value = response.data;
    
    console.log('获取食物数据成功:', foodList.value); // 调试日志
    
    // 数据加载完成后初始化图表
    await nextTick();
    initCharts();
  } catch (err) {
    error.value = '获取食物数据失败，请稍后重试';
    console.error('获取食物数据失败:', err);
  } finally {
    loading.value = false;
  }
});

// 初始化所有图表
const initCharts = () => {
  console.log('初始化图表，食物数量:', filteredFoods.value.length); // 调试日志
  
  filteredFoods.value.forEach((food, index) => {
    console.log(`尝试初始化食物图表，索引=${index}, ID=${food.food_id}`);
    
    nextTick(() => {
      const chartDom = chartRefs.value[index];
      console.log(`食物索引=${index}, ID=${food.food_id} 的图表容器:`, chartDom); // 调试日志
      
      if (chartDom) {
        // 创建图表实例
        const chart = echarts.init(chartDom);
        charts.value[food.food_id] = chart;
        
        // 设置图表选项
        const options = getChartOptions(food);
        console.log(`食物ID=${food.food_id} 的图表配置:`, options); // 调试日志
        
        chart.setOption(options);
        
        // 监听窗口大小变化，调整图表
        const resizeHandler = () => chart.resize();
        window.addEventListener('resize', resizeHandler);
        
        // 保存resize监听器引用，用于卸载时移除
        chart['__resizeHandler__'] = resizeHandler;
      } else {
        console.warn(`食物索引=${index}, ID=${food.food_id} 的图表容器未找到`);
      }
    });
  });
};

// 获取图表配置
const getChartOptions = (food) => {
  // 处理营养数据（确保数值有效性）
  const protein = parseFloat(food.protein) || 0;
  const fat = parseFloat(food.fat) || 0;
  const carbohydrate = parseFloat(food.carbohydrate) || 0;
  const total = protein + fat + carbohydrate;
  
  console.log(`构建图表配置 - 食物:${food.name}, 蛋白质:${protein}, 脂肪:${fat}, 碳水:${carbohydrate}, 总计:${total}`); // 调试日志
  
  // 空数据处理
  if (total === 0) {
    return {
      title: {
        text: '暂无营养数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 14
        }
      },
      series: []
    };
  }
  
  // 图表配置
  return {
    title: {
      text: '营养成分占比',
      subtext: `(${food.name})`,
      left: 'center',
      textStyle: { color: '#333' }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}g ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: ['蛋白质', '脂肪', '碳水化合物']
    },
    series: [
      {
        name: '营养成分',
        type: 'pie',
        radius: ['30%', '60%'], // 调整内圈和外圈半径比例，让饼图更大
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2,
          color: (params) => {
            const colorMap = {
              '蛋白质': NUTRITION_COLORS.protein,
              '脂肪': NUTRITION_COLORS.fat,
              '碳水化合物': NUTRITION_COLORS.carbohydrate
            };
            return colorMap[params.name] || '#ccc';
          }
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: [
          { value: protein, name: '蛋白质' },
          { value: fat, name: '脂肪' },
          { value: carbohydrate, name: '碳水化合物' }
        ]
      }
    ]
  };
};

// 监听搜索结果变化，更新图表
watch(filteredFoods, () => {
  console.log('搜索结果变化，重新初始化图表'); // 调试日志
  
  // 销毁旧图表
  Object.values(charts.value).forEach(chart => {
    if (chart['__resizeHandler__']) {
      window.removeEventListener('resize', chart['__resizeHandler__']);
    }
    chart.dispose();
  });
  charts.value = {};
  
  // 重新初始化图表
  nextTick(() => {
    initCharts();
  });
});

// 组件卸载时清理资源
onUnmounted(() => {
  console.log('组件卸载，销毁所有图表'); // 调试日志
  
  Object.values(charts.value).forEach(chart => {
    if (chart['__resizeHandler__']) {
      window.removeEventListener('resize', chart['__resizeHandler__']);
    }
    chart.dispose();
  });
  charts.value = {};
});

// 过滤食物
const filterFoods = () => {
  // 已通过计算属性实时过滤，此处无需额外逻辑
};
</script>

<style scoped>
.nutrition-page {
  font-family: 'Inter', sans-serif;
  background: url('your-bg-image-url.jpg') no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  padding: 20px;
  min-height: 100vh;
}

.header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

h1 {
  color: #333;
  font-size: 28px;
  margin: 0;
}

.search-bar {
  display: flex;
  gap: 8px;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
}

.search-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 24px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn i {
  margin-right: 4px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #4CAF50;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #ff4d4f;
  text-align: center;
  padding: 40px;
}

.food-cards {
  max-width: 1800px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(3, 2fr);
  gap: 24px;
  padding: 30px;
}

.food-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: transform 0.2s;
  padding: 32px;
  min-width: 300px;
}

.food-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.calories {
  font-size: 14px;
  color: #666;
}

.nutrition-facts {
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.fact-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.fact-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.fact-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.card-content-description {
  padding: 16px;
  border-bottom: none;
}

.card-content-description p {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

/* 营养成分图表样式 */
.nutrition-chart {
  height: 300px; /* 适当增大高度，从240px改为300px ，可按需调整 */
  width: 100%; /* 新增，让图表容器宽度撑满父元素 */
  padding: 10px;
  border-top: 1px solid #eee;
  background-color: #f8f9fa;
  border-radius: 0 0 12px 12px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
 .food-cards {
    grid-template-columns: repeat(3, 1fr);
    max-width: 100%;
  }
}
</style>